package data;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 *
 * @author Christian Morgan Andersen
 */
public class MySQLconnection {
    private Connection conn;
    private Statement stmt;
    private ResultSet rset;
   
    String login = new String("tomcat");
    String passwd = new String("password");
 
    public MySQLconnection() {
        establishConnection();
    }
   
    private void establishConnection()
    {
        Properties p = new Properties();
        p.setProperty("user", login);
        p.setProperty("password", passwd);
        p.setProperty("autoReconnect", "true");
       
        try
        {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/flibaview",p);
        }
            catch (Exception e)
            {
                System.out.println(e+"Problems with the database con");
               
            }
       
    }
    public Statement getStatement(){
        try{
            return conn.createStatement();
        }catch (SQLException sqle)
        {
            System.out.println("Forbindelse problemer, prøv igen eller kontakt admin");
         }
        return null;
    }
 
    public PreparedStatement prepareStatement(String sql){
        try{
            return conn.prepareStatement(sql);
        }catch (SQLException sqle){
            System.out.println("Forbindelse problemer, prøv igen eller kontakt admin");
        }
        return null;
    }
 
    public CallableStatement createCallableStatement(String sqlcall){
        try{
            return conn.prepareCall(sqlcall);
        }catch (SQLException sqle){
            System.out.println("Forbindelse problemer, prøv igen eller kontakt admin");
        }
        return null;
    }
 
    public ResultSet executeQuery(String sqlquery, String info) // bruges når man har brug for en retur værdi (feks hente noget data
    {
 
        stmt = getStatement();
        try
        {
            rset = stmt.executeQuery(sqlquery);
        }
        catch (SQLException sqle)
        {
            System.out.println("Advarsel\n Problem med "+info+"\n" +sqle);
        }
        return rset;
    }
 
    public void executeCommand(String sqlquery, String info)  // bruge når man ikke har brug for en retur værdi (feks når der slettes en post
    {
 
        stmt = getStatement();
        try
        {
            stmt.executeUpdate(sqlquery);
        }
        catch (SQLException sqle)
        {
            System.out.println("Advarsel\n Problem med "+info+"\n" +sqle);
        }
    }
   
    protected void finalize() throws Throwable {
        try {
            conn.close();
            super.finalize();
        }catch (SQLException sqle)
        {}   
    }
}
